<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  listAppVoByPageByAdmin,
  deleteAppByAdmin,
  updateAppByAdmin
} from '@/api/appController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import {
  SearchOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
  StarOutlined,
  EyeOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { getCodeGenTypeName, CODE_GEN_TYPE_OPTIONS } from '@/constants/codeGenType'
import AppStatusTag from '@/components/AppStatusTag.vue'
import DeleteConfirm from '@/components/DeleteConfirm.vue'
import UserInfo from '@/components/UserInfo.vue'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 默认标签选项
const defaultTags = [
  // 应用类型
  '网站', '工具', '游戏', '教育', '商务', '博客', '电商', '社交',
  // 技术栈
  'HTML', 'CSS', 'JavaScript', 'Vue', 'React', 'TypeScript',
  // 风格
  '简约', '现代', '创意', '专业', '可爱', '商务风',
  // 功能
  '管理系统', 'Landing Page', '移动端', '响应式', '交互式'
]

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
    width: 150,
  },
  {
    title: '封面',
    dataIndex: 'cover',
    width: 100,
  },
  {
    title: '生成类型',
    dataIndex: 'codeGenType',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    width: 80,
  },
  {
    title: '应用标签',
    dataIndex: 'tags',
    width: 150,
  },
  {
    title: '创建者',
    dataIndex: 'user',
    width: 120,
  },
  {
    title: '部署状态',
    dataIndex: 'deployKey',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
]

// 数据状态
const data = ref<API.AppVO[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索参数
const searchParams = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

/**
 * 获取应用列表数据
 */
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listAppVoByPageByAdmin({
      ...searchParams,
      sortField: 'createTime',  // 🔧 按创建时间排序
      sortOrder: 'desc'         // 🔧 倒序排列，最新的在前面
    })
    if (res.data.code === 0 && res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.totalRow ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    message.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

/**
 * 分页配置
 */
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

/**
 * 表格变化处理
 */
const doTableChange = (page: any) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

/**
 * 搜索处理
 */
const doSearch = () => {
  searchParams.pageNum = 1
  fetchData()
}

/**
 * 重置搜索
 */
const resetSearch = () => {
  searchParams.appName = undefined
  searchParams.codeGenType = undefined
  searchParams.userId = undefined
  searchParams.priority = undefined
  searchParams.pageNum = 1
  fetchData()
}

/**
 * 删除应用
 */
const doDelete = async (id: number) => {
  if (!id) return

  try {
    const res = await deleteAppByAdmin({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      fetchData()
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch (error) {
    message.error('删除失败，请检查网络连接')
  }
}

/**
 * 设置为精选应用
 */
const doSetFeatured = async (app: API.AppVO) => {
  if (!app.id) return

  try {
    const res = await updateAppByAdmin({
      id: app.id,
      appName: app.appName,
      cover: app.cover,
      priority: 99, // 设置优先级为99表示精选
    })
    if (res.data.code === 0) {
      message.success('设置精选成功')
      fetchData()
    } else {
      message.error('设置精选失败：' + res.data.message)
    }
  } catch (error) {
    message.error('设置精选失败，请检查网络连接')
  }
}

/**
 * 查看应用详情
 */
const viewApp = (app: API.AppVO) => {
  router.push(`/app/detail/${app.id}`)
}

/**
 * 编辑应用
 */
const editApp = (app: API.AppVO) => {
  router.push(`/app/edit/${app.id}`)
}

/**
 * 标签颜色映射
 */
const getTagColor = (tag: string) => {
  const colorMap: Record<string, string> = {
    '网站': 'blue',
    '工具': 'green',
    '游戏': 'purple',
    '教育': 'orange',
    '商务': 'gold',
    'Vue': '#4fc08d',
    'React': '#61dafb',
    'HTML': '#e34c26',
    'CSS': '#264de4',
    'JavaScript': '#f7df1e',
    '管理系统': 'orange',
    '博客': 'cyan',
    '电商': 'magenta',
    '社交': 'lime',
    '简约': 'geekblue',
    '现代': 'volcano',
    '创意': 'pink',
    '专业': 'purple'
  }
  return colorMap[tag] || 'default'
}

/**
 * 进入对话页面
 */
const enterChat = (app: API.AppVO) => {
  router.push(`/app/chat/${app.id}`)
}

// 页面加载时请求数据
onMounted(() => {
  // 检查管理员权限
  if (loginUserStore.loginUser.userRole !== 'admin') {
    message.error('您没有权限访问该页面')
    router.push('/')
    return
  }
  fetchData()
})
</script>

<template>
  <div id="appManagePage">
    <a-card class="app-manage-card" :bordered="false">

      <!-- 搜索表单 -->
      <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
        <a-form-item label="应用名称">
          <a-input
            v-model:value="searchParams.appName"
            placeholder="输入应用名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="生成类型">
          <a-select
            v-model:value="searchParams.codeGenType"
            placeholder="选择生成类型"
            allow-clear
            style="width: 150px"
          >
            <a-select-option
              v-for="option in CODE_GEN_TYPE_OPTIONS"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="优先级">
          <a-input-number
            v-model:value="searchParams.priority"
            placeholder="优先级"
            :min="0"
            :max="99"
            style="width: 100px"
          />
        </a-form-item>
        <a-form-item label="用户ID">
          <a-input-number
            v-model:value="searchParams.userId"
            placeholder="用户ID"
            :min="1"
            style="width: 100px"
          />
        </a-form-item>
        <a-form-item label="应用标签">
          <a-select
            v-model:value="searchParams.tags"
            mode="multiple"
            placeholder="选择标签筛选"
            allow-clear
            style="width: 200px"
          >
            <a-select-option
              v-for="tag in defaultTags"
              :key="tag"
              :value="tag"
            >
              {{ tag }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-divider style="margin: 16px 0" />

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        @change="doTableChange"
        :loading="loading"
        :rowKey="record => record.id"
        :scroll="{ x: 1200 }"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <!-- 应用名称 -->
          <template v-if="column.dataIndex === 'appName'">
            <div class="app-name-cell">
              <span class="app-name" @click="viewApp(record)">
                {{ record.appName || '未命名应用' }}
              </span>
            </div>
          </template>

          <!-- 封面 -->
          <template v-else-if="column.dataIndex === 'cover'">
            <div class="cover-cell">
              <img
                v-if="record.cover"
                :src="record.cover"
                :alt="record.appName"
                class="cover-image"
              />
              <div v-else class="no-cover">
                无封面
              </div>
            </div>
          </template>

          <!-- 生成类型 -->
          <template v-else-if="column.dataIndex === 'codeGenType'">
            <AppStatusTag :app="record" :show-priority="false" :show-deploy="false" />
          </template>

          <!-- 优先级 -->
          <template v-else-if="column.dataIndex === 'priority'">
            <AppStatusTag :app="record" :show-type="false" :show-deploy="false" />
          </template>

          <!-- 应用标签 -->
          <template v-else-if="column.dataIndex === 'tags'">
            <div class="tags-cell">
              <template v-if="record.tags && record.tags.length > 0">
                <a-tag
                  v-for="tag in record.tags.slice(0, 2)"
                  :key="tag"
                  :color="getTagColor(tag)"
                  size="small"
                >
                  {{ tag }}
                </a-tag>
                <a-tag v-if="record.tags.length > 2" size="small" style="color: #666">
                  +{{ record.tags.length - 2 }}
                </a-tag>
              </template>
              <span v-else class="no-tags">暂无标签</span>
            </div>
          </template>

          <!-- 创建者 -->
          <template v-else-if="column.dataIndex === 'user'">
            <UserInfo :user="record.user" :size="24" />
          </template>

          <!-- 部署状态 -->
          <template v-else-if="column.dataIndex === 'deployKey'">
            <a-tag v-if="record.deployKey" color="green">
              已部署
            </a-tag>
            <a-tag v-else color="default">
              未部署
            </a-tag>
          </template>

          <!-- 创建时间 -->
          <template v-else-if="column.dataIndex === 'createTime'">
            <a-tooltip :title="dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')">
              {{ dayjs(record.createTime).format('YYYY-MM-DD') }}
            </a-tooltip>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space size="small">
              <a-tooltip title="查看详情">
                <a-button type="primary" size="small" @click="viewApp(record)">
                  <template #icon><EyeOutlined /></template>
                </a-button>
              </a-tooltip>

              <a-tooltip title="编辑应用">
                <a-button size="small" @click="editApp(record)">
                  <template #icon><EditOutlined /></template>
                </a-button>
              </a-tooltip>

              <a-tooltip title="设为精选">
                <a-button
                  size="small"
                  @click="doSetFeatured(record)"
                  :disabled="record.priority === 99"
                >
                  <template #icon><StarOutlined /></template>
                </a-button>
              </a-tooltip>

              <DeleteConfirm
                :title="`确定要删除应用「${record.appName}」吗？`"
                @confirm="doDelete(record.id)"
              >
                <a-tooltip title="删除应用">
                  <a-button type="primary" danger size="small">
                    <template #icon><DeleteOutlined /></template>
                  </a-button>
                </a-tooltip>
              </DeleteConfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts">
</script>

<style scoped>
.app-manage-card {
  margin-bottom: 24px;
  box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16),
              0 3px 6px 0 rgba(0, 0, 0, 0.12),
              0 5px 12px 4px rgba(0, 0, 0, 0.09);
  border-radius: 8px;
}

.search-form {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 表格样式 */
:deep(.ant-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f0f5ff;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #e6f7ff;
}

:deep(.ant-pagination) {
  margin-top: 16px;
}

/* 应用名称单元格 */
.app-name-cell {
  display: flex;
  align-items: center;
}

.app-name {
  color: #1890ff;
  cursor: pointer;
  font-weight: 500;
}

.app-name:hover {
  text-decoration: underline;
}

/* 封面单元格 */
.cover-cell {
  display: flex;
  justify-content: center;
}

.cover-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

.no-cover {
  width: 40px;
  height: 40px;
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #8c8c8c;
}

/* 标签单元格 */
.tags-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.no-tags {
  color: #999;
  font-size: 12px;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  :deep(.ant-form-item) {
    margin-bottom: 12px;
  }

  :deep(.ant-table) {
    font-size: 12px;
  }
}
</style>
